package com.zhuqiandann.scis.controller;

import com.zhuqiandann.scis.common.JsonResult;
import com.zhuqiandann.scis.common.PageJson;
import com.zhuqiandann.scis.model.Question;
import com.zhuqiandann.scis.service.PaperService;
import com.zhuqiandann.scis.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/paper/question")
public class AdminQuestionController {
    @Autowired
    QuestionService questionService;
    @Autowired
    PaperService paperService;

    @GetMapping("/numlist")
    @ResponseBody
    public PageJson<Question> all(@RequestParam(required = true) Long num, ModelMap map){
        List<Question> questionList = questionService.findByPaper(num);
        PageJson<Question> page = new PageJson<>();
        page.setCode(0);
        page.setMsg("成功");
        page.setCount(questionList.size());
        page.setData(questionList);
        return page;
    }

    @GetMapping("/idlist")
    @ResponseBody
    public PageJson<Question> all(@RequestParam(required = true) Integer id, ModelMap map){
        List<Question> questionList = questionService.findByPaperid(id);
        PageJson<Question> page = new PageJson<>();
        page.setCode(0);
        page.setMsg("成功");
        page.setCount(questionList.size());
        page.setData(questionList);
        return page;
    }

    @GetMapping("/form")
    public String form(@RequestParam(required = false) Integer id, ModelMap map){

        if(id != null){
            Question question = questionService.findById(id);
            map.put("question",question);
        }
        return "admin/paper/question/form";
    }


    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Question question){
        try {
            questionService.saveOrUpdate(question);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

    @DeleteMapping("{id}/del")
    @ResponseBody
    public JsonResult del(@PathVariable("id") Integer id){
        try {
            questionService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail("删除失败");
        }
        return JsonResult.ok();
    }

}
